package com.fire.core.util;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fire.core.jkmodel.ReqDTO;
import com.fire.core.jkmodel.SmsInfoDTO;
import com.fire.core.jkmodel.XmlMessageDTO;

public class SendSmsCodeUtil {
	// 后续封装在配置表
    private static String PARTNER_CODE = "YiBaoTong";
    private static String SUCCESS_CODE = "0000";
    
    /**
     * 调金科短信验证码接口
     * @param mobileNo
     * @param smsCode
     * @param expireTimeInMinute
     * @param who
     * @return
     * @throws Exception
     */
    public AjaxResult sendSms(String mobileNo,String smsCode,int expireTimeInMinute,String who) throws Exception {
    	AjaxResult result = new AjaxResult();
        String requestId = GenratorNoHelper.generateRequestId();// 交易流水号，每次请求必须不一样;
        ReqDTO<SmsInfoDTO> reqDTO = new ReqDTO<>();
        reqDTO.setTransCode("sendSms");
        reqDTO.setPartnerCode(PARTNER_CODE);
        reqDTO.setRequestId(requestId);
        reqDTO.setTimestamp(System.currentTimeMillis());
        reqDTO.setReqData(getSmsInfoDTO(mobileNo,smsCode,expireTimeInMinute));
        String responseStr = JkSmsCodeUtils.postRequest(reqDTO,who);
        XmlMessageDTO xmlMessageDTO = XmlMessageUtil.parseXml(responseStr);
        boolean flag = JkSmsCodeUtils.checkSign(xmlMessageDTO);// 验证签名是否合法
        if (flag) {
        	JSONObject resultObj = JSON.parseObject(xmlMessageDTO.getContent());
        	if (SUCCESS_CODE.equals(resultObj.getString("resCode"))) {
        		 result.setMessage("验证码发送成功");
        		 result.setStatus("0");
        	}else {
        		String resultMsg = resultObj.getString("resMsg");
        		result.setMessage(resultMsg);
       		 	result.setStatus("1");
        	}
        }else {
        	result.setStatus("1");
            result.setMessage("签名验证失败");
        }
//        String jsonResStr = JSON.toJSONString(xmlMessageDTO.getContent());
//        System.out.println(jsonResStr);
//        RespDTO resDTO = JSON.parseObject(jsonResStr, RespDTO.class);
//        return resDTO;
        return result;
    }

    /**
     * 构造短信验证码请求结构
     * 
     * @return
     */
    private SmsInfoDTO getSmsInfoDTO(String mobileNo, String smsCode, int expireTimeInMinute) {
        SmsInfoDTO smsInfo = new SmsInfoDTO();
        smsInfo.setMobileNo(mobileNo);
        smsInfo.setSmsCode(smsCode);
        smsInfo.setExpireTimeInMinute(expireTimeInMinute);
        return smsInfo;
    }
    
    public static void main(String[] args) {
    	try {
	    	SendSmsCodeUtil utils = new SendSmsCodeUtil();
	    	utils.sendSms("15018527400","888888",10,"andyLau");
    	}catch(Exception e) {
    		e.printStackTrace();
    	}
    }
}
